<template>
  <div class="mind" :class="{'full-screen':!fullShow}" :ref="id">
      <div class="toolbar">
          <div class="toolbar-inner" v-if="!readOnly">
              <div class="toolbar-group">
                <button :disabled="retShow" @click="ret" class="tb-btn" title="撤销上一步操作 (Ctrl+Z)" @mouseover="showTooltip('撤销上一步操作')" @mouseout="hideTooltip()">
                  <i class="tb-icon tb-icon-undo"></i>
                  <span class="tb-label">撤销</span>
                </button>
                <button :disabled="forwardShow" @click="forward" class="tb-btn" title="重做上一步操作 (Ctrl+Y)" @mouseover="showTooltip('重做上一步操作')" @mouseout="hideTooltip()">
                  <i class="tb-icon tb-icon-redo"></i>
                  <span class="tb-label">重做</span>
                </button>
              </div>
              
              <div class="toolbar-group">
                <!-- <button @click="nodeStyle" class="tb-btn" title="设置节点文字、边框、背景和线条样式" @mouseover="showTooltip('设置节点样式，包括文字、边框、背景和线条')" @mouseout="hideTooltip()">
                  <i class="tb-icon tb-icon-format"></i>
                  <span class="tb-label">格式</span>
                </button> -->
              </div>
              
              <div class="toolbar-group">
                <button :disabled="mindShow" @click="addNode" class="tb-btn" title="添加子节点 - 在当前选中节点下添加子节点" @mouseover="showTooltip('添加子节点 - 在当前选中节点下添加新的子节点')" @mouseout="hideTooltip()">
                  <i class="tb-icon tb-icon-add"></i>
                  <span class="tb-label">添加子节点</span>
                </button>
                <button :disabled="mindShow" @click="brotherNode" class="tb-btn" title="添加平级节点 - 在当前节点同级添加新节点" @mouseover="showTooltip('添加平级节点 - 在当前节点同级添加新节点')" @mouseout="hideTooltip()">
                  <i class="tb-icon tb-icon-brother"></i>
                  <span class="tb-label">添加平级节点</span>
                </button>
                <button :disabled="mindShow" @click="delNode" class="tb-btn" title="删除节点 - 删除当前选中的节点及其子节点" @mouseover="showTooltip('删除节点 - 删除当前选中的节点及其子节点')" @mouseout="hideTooltip()">
                  <i class="tb-icon tb-icon-delete"></i>
                  <span class="tb-label">删除</span>
                </button>
              </div>
              
              <div class="toolbar-group">
                <!-- <button :disabled="mindShow" @click="associativeLine" class="tb-btn" title="添加关联线 - 连接两个不同分支的节点" @mouseover="showTooltip('添加关联线 - 连接两个不同分支的节点')" @mouseout="hideTooltip()">
                  <i class="tb-icon tb-icon-relation"></i>
                  <span class="tb-label">关联线</span>
                </button> -->
                <!-- <button class="tb-btn" title="插入公式 - 添加数学公式到节点中" @mouseover="showTooltip('插入公式 - 添加数学公式到节点中')" @mouseout="hideTooltip()">
                  <i class="tb-icon tb-icon-formula"></i>
                  <span class="tb-label">公式</span>
                </button> -->
                <!-- <button class="tb-btn" title="添加外框 - 为一组相关节点添加边框" @mouseover="showTooltip('添加外框 - 为一组相关节点添加边框')" @mouseout="hideTooltip()">
                  <i class="tb-icon tb-icon-frame"></i>
                  <span class="tb-label">外框</span>
                </button>
                <button class="tb-btn" title="添加备注 - 为节点添加详细说明文字" @mouseover="showTooltip('添加备注 - 为节点添加详细说明文字')" @mouseout="hideTooltip()">
                  <i class="tb-icon tb-icon-note"></i>
                  <span class="tb-label">备注</span>
                </button> -->
              </div>
              
              <div class="toolbar-group">
                <button @click="structure" class="tb-btn" title="切换布局方式 - 在思维导图、逻辑结构和组织结构间切换" @mouseover="showTooltip('切换布局方式 - 在思维导图、逻辑结构和组织结构间切换')" @mouseout="hideTooltip()">
                  <i class="tb-icon tb-icon-structure"></i>
                  <span class="tb-label">结构样式</span>
                </button>
              </div>
              
              <div class="toolbar-group">
                <button v-if="protectShow" @click="preservation" class="tb-btn" title="保存当前思维导图" @mouseover="showTooltip('保存当前思维导图')" @mouseout="hideTooltip()">
                  <i class="tb-icon tb-icon-save"></i>
                  <span class="tb-label">保存</span>
                </button>
                <button @click="fullTap" v-if="fullShow" class="tb-btn" title="进入全屏模式" @mouseover="showTooltip('进入全屏模式')" @mouseout="hideTooltip()">
                  <i class="tb-icon tb-icon-fullscreen"></i>
                  <span class="tb-label">全屏</span>
                </button>
                <button @click="fullDel" v-else class="tb-btn" title="退出全屏模式" @mouseover="showTooltip('退出全屏模式')" @mouseout="hideTooltip()">
                  <i class="tb-icon tb-icon-exit-fullscreen"></i>
                  <span class="tb-label">退出全屏</span>
                </button>
                <!-- <button class="tb-btn" title="使用AI助手辅助创建思维导图" @mouseover="showTooltip('使用AI助手辅助创建思维导图')" @mouseout="hideTooltip()">
                  <i class="tb-icon tb-icon-ai"></i>
                  <span class="tb-label">AI</span>
                </button> -->
              </div>
          </div>
          
          <!-- 添加工具栏提示区域 -->
          <div class="toolbar-desc" v-if="!readOnly">
              <div class="toolbar-tip-group">
                  <div class="toolbar-tip">历史操作</div>
              </div>
              <div class="toolbar-tip-group">
                  <div class="toolbar-tip">样式设置</div>
              </div>
              <div class="toolbar-tip-group">
                  <div class="toolbar-tip">节点编辑</div>
              </div>
              <div class="toolbar-tip-group">
                  <div class="toolbar-tip">高级功能</div>
              </div>
              <div class="toolbar-tip-group">
                  <div class="toolbar-tip">布局方式</div>
              </div>
              <div class="toolbar-tip-group">
                  <div class="toolbar-tip">系统功能</div>
              </div>
          </div>
          
          <!-- 添加按钮功能提示条 -->
          <div class="toolbar-tooltip" v-if="tooltipText && !readOnly">
              {{ tooltipText }}
          </div>
      </div>
      <div :id="id" class="mindMapContainer"></div>
      <div class="node-style" :ref="id+'e'" :class="{'node-s': trans, 'node-h': !trans}">
          <div class="style-li">
              <img @click="nodeStyle" src="" alt="" />
              <div class="style-title">文字</div>
              <div class="style-list">
                  <div class="node-left zIndex2">
                      <span>字号</span>
                      <Select :options="optionSize" v-model="sizeValue"></Select>
                  </div>
                  <div class="node-left padd zIndex2">
                      <span>行高</span>
                      <Select :options="optionRow" v-model="rowValue"></Select>
                  </div>
              </div>
              <div class="node-but">
                  <button @click="colorTap($event,'color')">颜色</button>
                  <button :style="{'background-color': (boldAct)? '#549688': '#fff','color': (boldAct)? '#fff': '#333'}"
                          @click="bolds">粗体
        </button>
                  <button :style="{'background-color': (italicAct)? '#549688': '#fff','color': (italicAct)? '#fff': '#333'}"
                          @click="italics">斜体
        </button>
                  <button :style="{'background-color': (scribeAct)? '#549688': '#fff','color': (scribeAct)? '#fff': '#333'}"
                          @click="scribes">划线
        </button>
      </div>
    </div>
          <div class="style-li">
              <div class="style-title">边框</div>
              <div class="style-list">
                  <div class="node-left">
                      <span>颜色</span>
                      <div @click="colorTap($event,'borderColor')" class="backColor"></div>
                  </div>
                  <div class="node-left padd zIndex3">
                      <span>样式</span>
                      <Select :options="optionLine" v-model="styleValue"></Select>
                  </div>
              </div>
              <div class="style-list">
                  <div class="node-left zIndex3">
                      <span>宽度</span>
                      <Select :options="optionWidth" v-model="widthValue"></Select>
                  </div>
                  <div class="node-left padd zIndex4">
                      <span>圆角</span>
                      <Select :options="optionWidth" v-model="filletValue"></Select>
                  </div>
              </div>
          </div>
          <div class="style-li">
              <div class="style-title">背景</div>
              <div class="style-list">
                  <div class="node-left">
                      <span>颜色</span>
                      <div @click="colorTap($event,'fillColor')" class="backColor"></div>
                  </div>
              </div>
          </div>
          <div class="style-li">
              <div class="style-title">线条</div>
              <div class="style-list">
                  <div class="node-left zIndex">
                      <span>宽度</span>
                      <Select :options="optionWidth" v-model="lineValue"></Select>
                  </div>
                  <div class="node-left padd zIndex">
                      <span>样式</span>
                      <Select :options="optionLine" v-model="lineStyleValue"></Select>
                  </div>
              </div>
              <div class="style-list">
                  <div class="node-left">
                      <span>颜色</span>
                      <div @click="colorTap($event,'lineColor')" class="backColor"></div>
                  </div>
              </div>
          </div>
          <div class="style-li">
              <div class="style-title">形状</div>
              <div class="style-list">
                  <div class="node-left">
                      <span>形状</span>
                      <Select :options="optionShape" v-model="shapeValue"></Select>
                  </div>
              </div>
          </div>
          <div class="back-col" :style="{top: top + 'px'}" v-if="colorShow">
              <Coloring @submit="submit" @empty="empty" @rgba="rgba" :color="color"></Coloring>
          </div>
    </div>
  </div>
</template>

<script>

import MindMap from "simple-mind-map";
import TouchEvent from 'simple-mind-map/src/plugins/TouchEvent.js'
import AssociativeLine from 'simple-mind-map/src/plugins/AssociativeLine.js'
import Drag from 'simple-mind-map/src/plugins/Drag.js'
import api from '@/api'
MindMap.usePlugin(AssociativeLine)
MindMap.usePlugin(TouchEvent)
MindMap.usePlugin(Drag)
export default {
  name: "zydx-mind",
  data() {
    return {
      id: null,
      mindMap: null,
      mindShow: false,
      retShow: false,
      forwardShow: false,
      tooltipText: '', // 添加提示文本
      optionSize: [
          {label: "12", value: '12'},
          {label: "14", value: '14'},
          {label: "16", value: '16'},
          {label: "18", value: '18'},
          {label: "20", value: '20'},
          {label: "24", value: '24'},
          {label: "26", value: '26'},
          {label: "28", value: '28'},
          {label: "30", value: '30'}
      ],
      sizeValue: '18',
      optionRow: [
          {label: "1", value: '1'},
          {label: "1.5", value: '1.5'},
          {label: "2", value: '2'},
          {label: "2.5", value: '2.5'},
          {label: "3", value: '3'}
      ],
      rowValue: '1.5',
      optionWidth: [
          {label: "0", value: 0},
          {label: "1", value: 1},
          {label: "2", value: 2},
          {label: "3", value: 3},
          {label: "4", value: 4},
          {label: "5", value: 5},
          {label: "6", value: 6},
          {label: "7", value: 7},
          {label: "8", value: 8},
          {label: "9", value: 9},
          {label: "10", value: 10},
      ],
      widthValue: 1,
      filletValue: '5',
      lineValue: '1',
      optionLine: [
          {label: "实线", value: 'none'},
          {label: "虚线", value: '5,5'},
          {label: "点线", value: '1,5'}
      ],
      lineStyleValue: 'none',
      styleValue: 'none',
      optionShape: [
          {label: "矩形", value: 'rectangle'},
          {label: "菱形", value: 'diamond'},
          {label: "平行四边形", value: 'parallelogram'},
          {label: "圆角矩形", value: 'roundedRectangle'},
          {label: "八角形", value: 'octagonalRectangle'},
          {label: "外三角矩形", value: 'outerTriangularRectangle'},
          {label: "内三角矩形", value: 'innerTriangularRectangle'},
          {label: "椭圆", value: 'ellipse'},
          {label: "圆", value: 'circle'},
      ],
      shapeValue: 'rectangle',
      trans: false,
      colorShow: false,
      top: 0,
      colorData: {},
      activeNodes: null,
      color: 'rgba(84,150,136,1)',
      boldAct: false,
      italicAct: false,
      scribeAct: false,
      defaultData: {
          "data": {
              "text": "根节点"
          },
          "children": []
      },
      fullShow: true,
      layoutList: 'logicalStructure',
      relationshipData: 'logicalStructure',
      // 自动保存相关
      autoSaveTimer: null,  // 自动保存定时器
      isAutoSaveEnabled: false,  // 是否启用自动保存
      autoSaveDelay: 60000,     // 自动保存间隔时间（毫秒）
      lastSaveTime: null,      // 最后保存时间
      changesSinceLastSave: false, // 上次保存后是否有变更
      industryNameamf: ''
    }
  },
  props: {
      data: { // 数据
          type: Object,
          default: {
              "data": {
                  "text": "根节点"
              },
              "children": []
          }
      },
      readOnly: { // 只读
          type: Boolean,
          default: false
      },
      protectShow: {
          type: Boolean,
          default: true
      },
      command: { // 接收父组件发送的命令
          type: Object,
          default: null
      },
      // autoSave: { // 是否启用自动保存
      //     type: Boolean,
      //     default: false
      // },
      autoSaveInterval: { // 自动保存间隔（毫秒）
          type: Number,
          default: 60000
      }
  },
  watch: {
      readOnly: {
          handler: function (val, oldVal) {
              this.mindMap?.setMode(val ? 'readonly' : 'edit')
          },
          deep: true,
          immediate: true
      },
      command: {
          handler: function(val) {
              if (val && val.type) {
                  this.logDataChange('接收到命令对象:', val);
                  this.receiveCommand(val.type, val.params);
              }
          },
          deep: true
      },
      data: {
          handler: function (val) {
              // 打印父组件传入的数据
              console.log('接收到父组件传入的数据:', JSON.stringify(val));
              
              if(Object.keys(val).length === 0) {
                  console.log('数据为空，使用默认数据');
                  this.mindMap?.setData(this.defaultData)
              } else {
                  // 检查是否存在关系数据
                  if (val.relations && Array.isArray(val.relations)) {
                      // 如果有关系数据，转换并应用
                      console.log('检测到关系数据:', val.relations);
                      this.relationshipData = val.relations.join(' ');
                      this.applyRelationshipData();
                  } else {
                      // 否则使用常规数据
                      console.log('使用常规数据，布局:', val.layoutList || 'logicalStructure');
                      this.mindMap?.setData(this.msgFun(val));
                      this.mindMap?.setLayout(val.layoutList || 'logicalStructure');
                  }
              }
          },
          immediate: true,
          deep: true
      },
      sizeValue(e) { // 字号
          this.activeNodes.forEach(node => {
              node.setStyle('fontSize', e)
          })
      },
      rowValue(e) { // 行高
          this.activeNodes.forEach(node => {
              node.setStyle('lineHeight', e)
          })
      },
      styleValue(e) { // 粗斜体
          this.activeNodes.forEach(node => {
              node.setStyle('borderDasharray', e)
          })
      },
      widthValue(e) { // 线宽
          this.activeNodes.forEach(node => {
              node.setStyle('borderWidth', e)
          })
      },
      filletValue(e) { // 圆角
          this.activeNodes.forEach(node => {
              node.setStyle('borderRadius', e)
          })
      },
      shapeValue(e) { // 形状
          this.activeNodes.forEach(node => {
              node.setStyle('shape', e)
          })
      },
      lineValue(e) { // 线宽
          this.activeNodes.forEach(node => {
              node.setStyle('lineWidth', e)
          })
      },
      lineStyleValue(e) { // 线宽
          this.activeNodes.forEach(node => {
              node.setStyle('lineDasharray', e)
          })
      },
  },
  mounted() {
      this.id = this.randomId()
      setTimeout(() => {
        this.init()
        // 如果存在关系数据，则在初始化完成后应用
        if (this.data.relations && Array.isArray(this.data.relations)) {
          setTimeout(() => {
            this.logDataChange('在mounted钩子中应用关系数据');
            this.relationshipData = this.data.relations.join(' ');
            this.applyRelationshipData();
          }, 300);  // 延迟稍微增加，确保思维导图已完全初始化
        }
      }, 0)
      window.onresize = () => {
        // 检查是否处于全屏状态
        const isFullScreen = !!(
          document.fullscreenElement || 
          document.mozFullScreenElement || 
          document.webkitFullscreenElement || 
          document.msFullscreenElement
        );
        
        // 更新全屏状态标志
        this.fullShow = !isFullScreen;
        
        // 调整思维导图大小
        if (this.mindMap) {
          this.mindMap.resize();
          
          // 如果全屏状态刚刚改变，重新计算布局以避免重叠问题
          if (!isFullScreen === this.fullShow) {
            setTimeout(() => {
              // 重置视图
              if (this.mindMap.view) {
                this.mindMap.view.setTransformData({
                  state: {scale: 1, x: 0, y: 0, sx: 0, sy: 0},
                  transform: {a:1,b:0,c:0,d:1,e:0,f:0,originX:0,originY:0,rotate:0,scaleX:1,scaleY:1,shear:0,translateX:0,translateY:0}
                });
              }
              
              // 重新计算布局
              this.mindMap.setLayout(this.layoutList || 'logicalStructure');
            }, 100);
          }
        }
      }
  },
  beforeUnmount() {
      // 组件销毁前清理定时器
      this.disableAutoSave();
      // 保存最终数据
      if (this.changesSinceLastSave && this.mindMap) {
          this.preservation();
      }
      this.logDataChange('思维导图组件销毁');
  },
  methods: {
    randomId() {
          const id = Math.random().toString(36).substr(2)
          return id.replace(/[0-9]/g, '')
    },
    fullScreen(element) {
        if (element.requestFullscreen) {
            element.requestFullscreen();
        } else if (element.webkitRequestFullscreen) {
            element.webkitRequestFullscreen();
        } else if (element.mozRequestFullScreen) {
            element.mozRequestFullScreen();
        } else if (element.msRequestFullscreen) {
            element.msRequestFullscreen();
        }
    },
    cancelFullscreen() {
        if (document.exitFullscreen) {
            document.exitFullscreen();
        } else if (document.webkitExitFullscreen) {
            document.webkitExitFullscreen();
        } else if (document.mozCancelFullScreen) {
            document.mozCancelFullScreen();
        } else if (document.msExitFullscreen) {
            document.msExitFullscreen();
        }
    },
    fullDel() {
        // 获取节点数量
        const nodeCount = this.countNodes(this.mindMap.getData());
        
        // 退出全屏
        this.cancelFullscreen();
        this.fullShow = true;
        
        // 等待DOM更新完成后重新调整大小
        this.$nextTick(() => {
            if (this.mindMap) {
                // 重置容器大小
                this.mindMap.resize();
                
                // 重新计算布局
                setTimeout(() => {
                    // 重置视图状态
                    this.mindMap.view.setTransformData({
                        state: {scale: 1, x: 0, y: 0, sx: 0, sy: 0},
                        transform: {
                            a: 1, b: 0, c: 0, d: 1, e: 0, f: 0,
                            originX: 0, originY: 0,
                            rotate: 0,
                            scaleX: 1, scaleY: 1,
                            shear: 0,
                            translateX: 0, translateY: 0
                        }
                    });
                    
                    // 适应视图
                    this.mindMap.command.exec('FIT_VIEW');
                }, 300);
            }
        });
    },
    fullTap() {
        // 获取思维导图容器
        const container = this.$refs[this.id];
        if (!container) {
            console.error('找不到思维导图容器');
            return;
        }
        
        // 设置全屏标志
        this.fullShow = false;
        
        // 进入全屏前保存当前状态和数据
        const currentData = this.mindMap?.getData();
        
        // 进入全屏
        this.fullScreen(container);
        
        // 等待DOM更新和全屏转换完成
        setTimeout(() => {
            if (this.mindMap) {
                // 重置容器大小
                this.mindMap.resize();
                
                // 如果有保存的数据,重新应用
                if (currentData) {
                    this.mindMap.setData(currentData);
                }
                
                // 重新计算布局并适应视图
                this.mindMap.setLayout(this.layoutList || 'logicalStructure');
                this.mindMap.command.exec('FIT_VIEW');
            }
        }, 300);
    },
    msgFun(e) {
         if(e.msg) {
           return Object.keys(e.msg).length === 0 ? this.defaultData : e.msg
         }else {
           return Object.keys(e).length === 0 ? this.defaultData : e
         }
      },
      
      // 调试函数：记录数据变化
      logDataChange(message, data) {
        console.log(`[思维导图] ${message}`, data ? JSON.stringify(data).substring(0, 300) + '...' : '');
      },
      // 初始化
      init() {
          const that = this
          
          // 判断是否有关系数据
          const hasRelations = that.data && that.data.relations && Array.isArray(that.data.relations) && that.data.relations.length > 0;
          
          // 如果有关系数据，先解析出初始数据
          let initialData = that.defaultData;
          if (hasRelations) {
              this.logDataChange('初始化时检测到关系数据');
              that.relationshipData = that.data.relations.join(' ');
              try {
                  initialData = that.parseRelationshipData(that.relationshipData);
              } catch (error) {
                  this.logDataChange('初始化时解析关系数据失败:', error);
              }
          } else {
              initialData = that.msgFun(that.data);
              this.industryNameamf = initialData.data.text
          }
          
          this.mindMap = new MindMap({
              el: document.getElementById(that.id),
              enableFreeDrag: true, // 是否开启自由拖拽
              enableNodeTransitionMove: true, // 是否开启节点过渡动画
              layout: hasRelations ? 'mindMap' : (that.data.layoutList || 'logicalStructure'), // 节点布局方式
              maxHistoryCount: 100, // 最大历史记录数
              maxNodeCacheCount: 100, // 最大节点缓存数
              data: initialData,
              // 启用节点拖拽功能
              enableDrag: true, // 允许拖拽节点
              draggable: true, // 允许拖动节点
              dragWhenNodeActive: true, // 节点激活时即可拖动
              allowAutoLayoutWhenDragEnd: false, // 拖拽结束后不自动调整布局
              overflowHidden: false // 内容溢出时不隐藏
          });
          
          this.logDataChange('MindMap初始化完成，布局', hasRelations ? 'mindMap' : (that.data.layoutList || 'logicalStructure'));
          
          this.mindMap.setMode(this.readOnly ? 'readonly' : 'edit')
          this.mindMap.on('node_active', (node) => {
              this.mindShow = node === null;
          })
          this.mindMap.on('back_forward', (index, len) => {
              this.retShow = index <= 0;
              this.forwardShow = index >= len - 1
          })
          this.mindMap.on('node_active', (node, activeNodeList) => {
              this.logDataChange('节点被激活', { node: node?.getData()?.text, activeCount: activeNodeList?.length });
              this.activeNodes = activeNodeList
              if (node) {
              const nodeData = node.getData();
              console.log('节点文本:', nodeData.text);
              api.user.nodearticles({
                node_name: nodeData.text,
                chain_name: this.industryNameamf
              }).then(res => {
                console.log(res, "res");
                const topic = {
                  topic: {
                    title: res.data.chain_name || "产业链分析",
                    totalArticleCount: res.data.total_articles,
                    // nodeTitle: nodeData.text,
                    // type: "industry",
                    // articleCount: res.data.node_articles?.length || 0,
                    // analysisCount: 0
                  },
                  articles: res.data.node_articles || []
                };
                this.$root.$emit('update-sidebar', topic)
              })
              console.log('节点ID:', nodeData.id);
              console.log('节点样式:', nodeData.style);
              console.log('完整节点数据:', nodeData);
    }
              console.log(node,this.activeNodes, "node");
          })
          this.mindMap.on('data_change', (data) => {
              this.logDataChange('数据发生变更');
              this.changesSinceLastSave = true; // 标记有数据变更
              this.industryNameamf = data.data.text
              this.$emit('dataChange', {
                  data: data,
                  url: ''
              })
          })
          
          // 添加拖拽相关事件监听
          this.mindMap.on('node_drag', (node, event) => {
              this.logDataChange('节点正在拖拽', { text: node.getData().text });
          })
          
          this.mindMap.on('node_drag_end', (node, event) => {
              this.logDataChange('节点拖拽结束', { text: node.getData().text });
              this.changesSinceLastSave = true; // 标记有数据变更
              // 发送数据变更事件
              this.$emit('dataChange', {
                  data: this.mindMap.getData(),
                  url: ''
              })
          })
          
          // 如果启用了自动保存，初始化自动保存
          if (this.autoSave) {
              this.enableAutoSave(this.autoSaveInterval);
          }
      },
      scribes() {
          this.scribeAct = !this.scribeAct
          this.activeNodes.forEach(node => {
              node.setStyle('textDecoration', (!this.scribeAct) ? 'none' : 'underline')
          })
      },
      italics() {
          this.italicAct = !this.italicAct
          this.activeNodes.forEach(node => {
              node.setStyle('fontStyle', (!this.italicAct) ? 'normal' : 'italic')
          })
      },
      bolds() {
          this.boldAct = !this.boldAct
          this.activeNodes.forEach(node => {
              node.setStyle('fontWeight', (!this.boldAct) ? 'normal' : 'bold')
          })
      },
      rgba(e) {
          this.colorData.data.target.style.backgroundColor = e.rgba
      },
      submit(e) {
          this.activeNodes.forEach(node => {
              node.setStyle(this.colorData.index, e.rgba)
          })
          this.colorData.data.target.style.backgroundColor = e.rgba
          this.colorShow = false
      },
      empty() {
          this.colorShow = false
      },
      colorTap(e, i) {
          this.colorData = {index: i, data: e}
          let parent = this.colorData.data.target.parentNode.offsetTop + 32
          if (parent > 330) parent = 300
          this.colorShow = !this.colorShow
          this.top = parent
      },
      structure() {
          this.layoutList = 'logicalStructure'
          const layout = this.mindMap.getLayout()
          if (layout === 'mindMap') {
            this.layoutList = 'organizationStructure'
          } else if (layout === 'organizationStructure') {
            this.layoutList = 'logicalStructure'
          } else {
            this.layoutList = 'mindMap'
          }
          this.mindMap.setLayout(this.layoutList)
      },
      // 保存
      preservation() {
          let that = this
          
          // 获取当前思维导图数据
          const mindMapData = that.mindMap.getData();
          
          // 确定当前数据类型和结构
          let saveData = {};
          
          // 如果原始数据包含关系型数据格式
          if (this.data && this.data.relations) {
              this.logDataChange('保存关系型思维导图数据');
              
              // 从当前思维导图状态重建关系数据
              const { relations, nodes, industryName } = this.rebuildRelationsFromMindMap(mindMapData);
              
              // 构建保存数据
              saveData = {
                  relations: relations,
                  // nodes为节点名称数组 ["OpenAI", "上游", "中游", ...]
                  nodes: nodes, 
                  industry_name: industryName
              };
              
              // 当只有根节点且没有关系时，确保relations不为空数组
              if (relations.length === 0 && nodes.length > 0) {
                  // 添加一个空的关系，或者可以创建一个自我引用
                  // 这取决于后端如何处理空relations数组
                  const rootId = mindMapData.data.id || '1';
                  const rootText = mindMapData.data.text;
                  
                  // 添加一个伪关系，确保saveData.relations不是空数组
                  // 此关系表明根节点是自己的一部分
                  saveData.relations = [`${rootText}-${rootId},${rootText}-${rootId},part-of`];
                  this.logDataChange('只有根节点，添加伪关系防止空数组');
              }
              
              this.logDataChange('重建的关系数据', relations);
              this.logDataChange('重建的节点数据', nodes);
              this.logDataChange('行业名称', saveData.industry_name);
          } else {
              // 常规思维导图数据
              const mindMapData = that.mindMap.getData();
              
              // 打印保存的数据
              this.logDataChange('保存常规思维导图数据');
              this.logDataChange('思维导图结构', mindMapData);
              
              // 使用与原始数据相同的结构
              if (this.data && this.data.msg) {
                  // 如果原始数据包含msg字段
                  saveData = {
                      data: {
                          msg: mindMapData,
                          layoutList: this.layoutList
                      },
                      url: ''
                  };
              } else {
                  // 常规结构
                  saveData = {
                      msg: mindMapData,
                      layoutList: this.layoutList
                  };
              }
              
              // 统计节点信息
              const nodeCount = this.countNodes(mindMapData);
              this.logDataChange(`保存时常规数据节点总数: ${nodeCount}`);
          }
          
          // 发送保存事件
          that.$emit('preservation', saveData);
          
          // 确认保存成功
          this.logDataChange('思维导图保存成功', saveData);
          console.log('思维导图保存成功', saveData);
          api.user.storestructure(saveData).then(res => {
            console.log('保存成功', res);
          })
          
          // 重置变更标记
          this.changesSinceLastSave = false;
          this.lastSaveTime = new Date();
      },
      getContent() {
          let that = this
          return new Promise((resolve, reject) => {
              try {
                  const data = that.mindMap.getData();
                  let result;
                  
                  // 判断原始数据是否包含relations
                  if (that.data && that.data.relations && Array.isArray(that.data.relations)) {
                      // 从当前思维导图状态重建关系数据
                      const { relations, nodes, industryName } = this.rebuildRelationsFromMindMap(data);
                      
                      // 构建返回数据
                      result = {
                          relations: relations,
                          nodes: nodes,
                          industry_name: industryName || that.data.industry_name || "OpenAI",
                          layoutList: this.layoutList
                      };
                      this.logDataChange('获取关系型思维导图内容', result);
                  } else {
                      // 常规思维导图数据
                      // 使用与原始数据相同的结构
                      if (that.data && that.data.msg) {
                          // 如果原始数据包含msg字段
                          result = {
                              data: {
                                  msg: data,
                                  layoutList: this.layoutList
                              },
                              url: ''
                          };
                      } else {
                          // 常规结构
                          result = {
                              data: data,
                              url: '',
                              layoutList: this.layoutList
                          };
                      }
                      this.logDataChange('获取常规思维导图内容', result);
                  }
                  
                  resolve(result);
              } catch (error) {
                  this.logDataChange('获取思维导图内容出错', error);
                  reject(error);
              }
          })
      },
      
      // 从当前思维导图状态重建关系数据
      rebuildRelationsFromMindMap(mindMapData) {
          const relations = [];
          // nodes应该是一个节点名称数组: ["OpenAI", "上游", "中游", ...]
          const nodesArray = []; 
          // 临时使用对象来去重和跟踪已处理的节点
          const processedNodes = {};
          let industryName = '';
          
          try {
              // 如果不存在数据，返回空结果
              if (!mindMapData || !mindMapData.data) {
                  return { relations, nodes: [], industryName };
              }
              
              // 获取根节点信息
              const rootNode = mindMapData.data;
              industryName = rootNode.text;
              const rootId = rootNode.id || '1';
              
              // 将根节点添加到节点数组 - 即使只有根节点也要添加
              if (!processedNodes[rootNode.text]) {
                  nodesArray.push(rootNode.text);
                  processedNodes[rootNode.text] = true;
              }
              
              // 递归处理所有子节点，构建关系数据
              const processChildren = (children, parentId, parentText) => {
                  if (!children || !Array.isArray(children) || children.length === 0) return;
                  
                  children.forEach(child => {
                      if (!child.data) return;
                      
                      const childId = child.data.id || Math.floor(Math.random() * 10000).toString();
                      const childText = child.data.text;
                      
                      // 确保节点有ID
                      if (!child.data.id) {
                          child.data.id = childId;
                      }
                      
                      // 将节点名称添加到数组中（避免重复）
                      if (!processedNodes[childText]) {
                          nodesArray.push(childText);
                          processedNodes[childText] = true;
                      }
                      
                      // 创建关系数据
                      const relation = `${childText}-${childId},${parentText}-${parentId},part-of`;
                      relations.push(relation);
                      
                      // 处理子节点的子节点
                      if (child.children && child.children.length > 0) {
                          processChildren(child.children, childId, childText);
                      }
                  });
              };
              
              // 从根节点开始处理
              processChildren(mindMapData.children, rootId, rootNode.text);
              
              // 如果没有任何关系（只有根节点），需要特殊处理
              if (relations.length === 0 && nodesArray.length > 0) {
                  // 保持根节点信息，确保nodes数组中至少有根节点
                  this.logDataChange('只有根节点，没有子节点关系');
              }
              
              // 返回结果
              return { 
                  relations, 
                  // 返回节点名称数组 ["OpenAI", "上游", "中游", ...]
                  nodes: nodesArray, 
                  industryName 
              };
              
          } catch (error) {
              this.logDataChange('重建关系数据时出错', error);
              return { relations, nodes: [], industryName };
          }
      },
      nodeStyle() {
          this.$refs[`${this.id}e`].style.display = 'block'
          this.$refs[this.id].style.overflow = 'hidden'
          this.trans = !this.trans
      setTimeout(() => {
              this.$refs[this.id].style.overflow = 'visible'
              if (!this.trans) {
                  this.$refs[`${this.id}e`].style.display = 'none'
              }
          }, 250)
      },
      // 关联线
      associativeLine() {
          this.mindMap.associativeLine.createLineFromActiveNode()
      },
      // 前进
      forward() {
          this.mindMap.execCommand('FORWARD')
      },
      // 返回
      ret() {
          this.mindMap.execCommand('BACK')
      },
      // 添加节点
      addNode() {
          this.mindMap.execCommand('INSERT_CHILD_NODE')
      },
      // 删除节点
      delNode() {
          this.mindMap.execCommand('REMOVE_NODE')
      },
      // 兄弟节点
      brotherNode() {
          this.mindMap.execCommand('INSERT_NODE')
      },
      // 应用关系数据
      applyRelationshipData() {
          if (!this.relationshipData || !this.mindMap) return;
          
          try {
              this.logDataChange('开始应用关系数据...');
              this.logDataChange('关系数据示例', this.relationshipData.split(/\s+/).slice(0, 3).join(' '));
              
              const data = this.parseRelationshipData(this.relationshipData);
              this.logDataChange('解析后的数据结构', data);
              
              this.mindMap.setData(data);
              
              // 设置合适的布局方式 - 尝试不同的布局选项
              // 可以根据节点数量选择不同的布局
              const nodeCount = this.countNodes(data);
              this.logDataChange(`节点总数: ${nodeCount}`);
              
              // 对于深海探索数据，使用思维导图布局效果最佳
              this.layoutList = 'mindMap';
              this.logDataChange(`使用布局: ${this.layoutList}`);
              
              this.mindMap.setLayout(this.layoutList);
              
              // 自动调整视图，以适应完整的思维导图
              setTimeout(() => {
                  this.logDataChange('调整视图以适应全部内容');
                  this.mindMap.command.exec('FIT_VIEW');
              }, 100);
              
          } catch (error) {
              this.logDataChange('应用关系数据时出错', error);
          }
      },
      
      // 计算节点总数
      countNodes(data) {
          let count = 0;
          const countRecursive = (node) => {
              count++;
              if (node.children && node.children.length > 0) {
                  node.children.forEach(countRecursive);
              }
          };
          countRecursive(data);
          return count;
      },
      
      // 将关系数据解析为思维导图数据结构
      parseRelationshipData(relationshipStr) {
          // 如果字符串为空，返回默认数据
          if (!relationshipStr || relationshipStr.trim() === '') {
              this.logDataChange('关系数据为空，使用默认数据');
              return this.defaultData;
          }

          try {
              this.logDataChange('开始解析关系数据');
              
              // 拆分关系数据并解析
              // 格式样例: "上游-2,OpenAI-1,part-of"，表示上游节点的ID是2，其父节点是OpenAI(ID为1)，关系类型是part-of
              const relationTriples = relationshipStr.split(/\s+/).filter(s => s.trim());
              const relationshipArray = [];
              
              // 用于存储所有节点，key是nodeId，value是节点对象
              const nodesMap = new Map();
              // 记录所有出现的节点ID
              const allNodeIds = new Set();
              // 用于记录出现的父节点ID及其引用次数
              const parentRefCount = new Map();
              
              relationTriples.forEach(triple => {
                  const parts = triple.split(',');
                  if (parts.length === 3) {
                      const sourceInfo = parts[0].split('-');
                      const targetInfo = parts[1].split('-');
                      const relationType = parts[2];
                      
                      if (sourceInfo.length >= 2 && targetInfo.length >= 2) {
                          const sourceId = sourceInfo[1];
                          const sourceName = sourceInfo[0];
                          const targetId = targetInfo[1];
                          const targetName = targetInfo[0];
                          
                          // 记录出现的节点ID
                          allNodeIds.add(sourceId);
                          allNodeIds.add(targetId);
                          
                          // 统计每个父节点的被引用次数
                          if (!parentRefCount.has(targetId)) {
                              parentRefCount.set(targetId, 0);
                          }
                          parentRefCount.set(targetId, parentRefCount.get(targetId) + 1);
                          
                          // 创建关系对象
                          const relationObj = {
                              id: sourceId,
                              text: sourceName,
                              parentId: targetId,  // 父节点ID
                              parentText: targetName,  // 父节点名称
                              relationType: relationType
                          };
                          
                          relationshipArray.push(relationObj);
                          
                          // 保存节点信息到nodesMap
                          if (!nodesMap.has(sourceId)) {
                              nodesMap.set(sourceId, {
                                  id: sourceId,
                                  text: sourceName,
                                  children: []
                              });
                          }
                          
                          if (!nodesMap.has(targetId)) {
                              nodesMap.set(targetId, {
                                  id: targetId,
                                  text: targetName,
                                  children: []
                              });
                          }
                      }
                  }
              });
              
              this.logDataChange(`解析到 ${relationshipArray.length} 个关系`);
              
              // 如果没有解析到任何关系，使用默认数据
              if (relationshipArray.length === 0) {
                  this.logDataChange('未解析到任何有效关系，使用默认数据');
                  return this.defaultData;
              }
              
              // 确定根节点的策略:
              // 根据ID的值确定根节点 - ID值较小的节点（特别是0、1）通常是根节点
              let rootNodeId = null;
              
              // 按照ID的数值大小排序，选择最小的ID作为根节点
              const sortedIds = Array.from(allNodeIds).sort((a, b) => parseInt(a) - parseInt(b));
              if (sortedIds.length > 0) {
                  rootNodeId = sortedIds[0];
                  this.logDataChange(`根据ID值选择节点 ${rootNodeId} 作为根节点`);
              }
              
              // 如果节点映射中存在ID为0或1的节点，优先使用它们作为根节点
              if (nodesMap.has('0')) {
                  rootNodeId = '0';
                  this.logDataChange('找到ID为0的节点，将其设为根节点');
              } else if (nodesMap.has('1')) {
                  rootNodeId = '1';
                  this.logDataChange('找到ID为1的节点，将其设为根节点');
              }
              
              // 获取根节点对象
              let rootNode = nodesMap.get(rootNodeId);
              
              // 如果根节点仍然未找到，使用默认数据
              if (!rootNode) {
                  this.logDataChange('未找到根节点，使用默认数据');
                  return this.defaultData;
              }
              
              this.logDataChange(`确定根节点为: ${rootNode.text}(ID: ${rootNode.id})`);
              
              // 构建思维导图数据结构
              const mindMapData = {
                  data: {
                      text: rootNode.text,
                      id: rootNode.id,
                      expanded: true,
                      // 为根节点添加特殊样式
                      style: {
                          fillColor: '#e0f7fa',
                          fontWeight: 'bold',
                          fontSize: '18',
                          borderColor: '#0288d1',
                          borderWidth: 2,
                          borderRadius: 5
                      }
                  },
                  children: []
              };
              
              // 递归构建节点树
              const processedNodes = new Set(); // 防止循环引用
              
              const buildNodeTree = (parentId) => {
                  if (processedNodes.has(parentId)) {
                      this.logDataChange(`检测到循环引用: 节点 ID ${parentId} 已经被处理过`);
                      return [];
                  }
                  
                  processedNodes.add(parentId);
                  
                  // 找出所有以parentId为父节点的关系
                  const childRelations = relationshipArray.filter(item => item.parentId === parentId);
                  
                  return childRelations.map(relation => {
                      // 根据关系类型设置不同的样式
                      let style = {};
                      let lineStyle = {};
                      
                      if (relation.relationType === 'is-a') {
                          // is-a关系使用虚线和红色
                          lineStyle = {
                              lineColor: '#FF6666',
                              lineDasharray: '5,5'
                          };
                          style = {
                              borderColor: '#FF6666',
                              fillColor: '#FFF0F0',
                              borderRadius: 5
                          };
                      } else if (relation.relationType === 'part-of') {
                          // part-of关系使用实线和蓝色
                          lineStyle = {
                              lineColor: '#6666FF',
                              lineDasharray: 'none'
                          };
                          style = {
                              borderColor: '#6666FF',
                              fillColor: '#F0F0FF',
                              borderRadius: 5
                          };
                      }
                      
                      // 特殊节点的样式
                      if (relation.text.includes('李培鑫')) {
                          style = {
                              ...style,
                              fillColor: '#f8bbd0',
                              borderColor: '#c2185b',
                              fontWeight: 'bold'
                          };
                      }
                      
                      return {
                          data: {
                              text: relation.text,
                              id: relation.id,
                              expanded: true,
                              style: style,
                              lineStyle: lineStyle
                          },
                          children: buildNodeTree(relation.id)
                      };
                  });
              };
              
              mindMapData.children = buildNodeTree(rootNode.id);
              this.logDataChange('思维导图数据构建完成');
              return mindMapData;
              
          } catch (error) {
              this.logDataChange('解析关系数据时出错', error);
              return this.defaultData;
          }
      },
      // 应用父组件传来的命令
      receiveCommand(command, params) {
        this.logDataChange(`接收到父组件命令: ${command}`, params);
        
        switch(command) {
          case 'refresh':
            // 刷新思维导图
            if (this.mindMap) {
              this.mindMap.refresh();
              this.logDataChange('已刷新思维导图');
            }
            break;
            
          case 'setData':
            // 设置新数据
            if (this.mindMap && params) {
              this.mindMap.setData(params);
              this.logDataChange('已设置新数据到思维导图');
            }
            break;
            
          case 'fitView':
            // 适应视图
            if (this.mindMap) {
              setTimeout(() => {
                this.mindMap.command.exec('FIT_VIEW');
                this.logDataChange('已调整视图以适应内容');
              }, 100);
            }
            break;
            
          case 'setLayout':
            // 设置布局
            if (this.mindMap && params) {
              this.mindMap.setLayout(params);
              this.layoutList = params;
              this.logDataChange(`已设置布局为: ${params}`);
            }
            break;
            
          case 'exportData':
            // 导出数据
            if (this.mindMap) {
              const data = this.mindMap.getData();
              this.$emit('exportData', data);
              this.logDataChange('已导出思维导图数据');
            }
            break;
            
          case 'save':
            // 手动保存
            this.preservation();
            break;
            
          case 'exportJson':
            // 导出为JSON文件
            this.exportToJson();
            break;
          
          case 'enableAutoSave':
            // 启用自动保存
            this.enableAutoSave(params || this.autoSaveInterval);
            break;
            
          case 'disableAutoSave':
            // 禁用自动保存
            this.disableAutoSave();
            break;
            
          default:
            this.logDataChange(`未知命令: ${command}`);
        }
        
        return true; // 返回处理结果
      },
      // 自动保存功能
      autoSave() {
          // 检查是否初始化
          if (!this.mindMap) {
              this.logDataChange('自动保存失败：思维导图未初始化');
              return;
          }
          
          // 使用与preservation方法相同的逻辑确定数据结构
          let saveData = {};
          
          // 判断原始数据是否包含relations
          if (this.data && this.data.relations && Array.isArray(this.data.relations)) {
              // 如果原始数据包含关系型数据，保持相同结构
              const mindMapData = this.mindMap.getData();
              
              // 保持与原始数据相同的结构
              saveData = {
                  relations: this.data.relations,
                  layoutList: this.layoutList
              };
          } else {
              // 常规思维导图数据
              const mindMapData = this.mindMap.getData();
              
              // 使用与原始数据相同的结构
              if (this.data && this.data.msg) {
                  // 如果原始数据包含msg字段
                  saveData = {
                      data: {
                          msg: mindMapData,
                          layoutList: this.layoutList
                      },
                      url: ''
                  };
              } else {
                  // 常规结构
                  saveData = {
                      msg: mindMapData,
                      layoutList: this.layoutList
                  };
              }
          }
          
          this.logDataChange('自动保存思维导图数据', saveData);
          
          // 发送自动保存事件
          // this.$emit('autoSave', saveData);
          
          // 重置变更标记
          this.changesSinceLastSave = false;
          this.lastSaveTime = new Date();
          
          return saveData;
      },
      
      // 导出思维导图数据为JSON
      exportToJson() {
          if (!this.mindMap) {
              this.logDataChange('导出JSON失败：思维导图未初始化');
              return null;
          }
          
          try {
              const data = this.mindMap.getData();
              const jsonStr = JSON.stringify(data, null, 2);
              
              this.logDataChange('导出思维导图为JSON');
              
              // 创建Blob对象
              const blob = new Blob([jsonStr], { type: 'application/json' });
              const url = URL.createObjectURL(blob);
              
              // 创建下载链接
              const a = document.createElement('a');
              a.href = url;
              a.download = '思维导图_' + new Date().getTime() + '.json';
              document.body.appendChild(a);
              a.click();
              
              // 清理
              setTimeout(() => {
                  document.body.removeChild(a);
                  URL.revokeObjectURL(url);
              }, 0);
              
              return data;
          } catch (error) {
              this.logDataChange('导出JSON时出错', error);
              return null;
          }
      },
      // 启用自动保存
      enableAutoSave(interval = 60000) {
          if (this.autoSaveInterval) {
              this.disableAutoSave(); // 先清除现有定时器
          }
          
          this.isAutoSaveEnabled = true;
          this.autoSaveDelay = interval;
          this.logDataChange(`启用自动保存，间隔 ${interval/1000} 秒`);
          
          // 设置定时器
          this.autoSaveTimer = setInterval(() => {
              if (this.changesSinceLastSave) {
                  // this.autoSave();
                  this.changesSinceLastSave = false;
                  this.lastSaveTime = new Date();
              } else {
                  this.logDataChange('自动保存检查：无变更，不需要保存');
              }
          }, interval);
          
          return true;
      },
      
      // 禁用自动保存
      disableAutoSave() {
          if (this.autoSaveTimer) {
              clearInterval(this.autoSaveTimer);
              this.autoSaveTimer = null;
          }
          
          this.isAutoSaveEnabled = false;
          this.logDataChange('已禁用自动保存');
          
          return true;
      },
      
      // 添加显示提示的方法
      showTooltip(text) {
          this.tooltipText = text;
      },
      
      // 添加隐藏提示的方法
      hideTooltip() {
          this.tooltipText = '';
      },
  }
}
</script>

<style scoped>
.mind {
  width: 100%;
  height: 100%;
  position: relative;
}

.toolbar {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  z-index: 10;
  padding: 5px 10px;
  margin-bottom: 10px;
  border: 1px solid #e8e8e8;
}

.toolbar-inner {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  position: relative;
}

.toolbar-group {
  display: flex;
  align-items: center;
  border-right: 1px solid #e0e0e0;
  padding: 0 5px;
  margin-right: 5px;
}

.toolbar-group:last-child {
  border-right: none;
}

.tb-btn {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 50px;
  height: 50px;
  background-color: transparent;
  border: none;
  border-radius: 4px;
  transition: all 0.2s ease;
  margin: 0 2px;
  padding: 5px 0;
  cursor: pointer;
  position: relative;
}

.tb-btn:hover:not(:disabled) {
  background-color: #f5f5f5;
  transform: translateY(-2px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.tb-btn:active:not(:disabled) {
  background-color: #e0e0e0;
  transform: translateY(0);
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.tb-btn:disabled {
  opacity: 0.4;
  cursor: not-allowed;
}

.tb-icon {
  width: 22px;
  height: 22px;
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center;
  opacity: 0.8;
}

.tb-btn:hover:not(:disabled) .tb-icon {
  opacity: 1;
}

.tb-label {
  font-size: 12px;
  margin-top: 5px;
  color: #666;
  white-space: nowrap;
  text-align: center;
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 图标样式 - 使用背景图片 */
.tb-icon-add {
  background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="12" y1="5" x2="12" y2="19"></line><line x1="5" y1="12" x2="19" y2="12"></line></svg>');
}

.tb-icon-brother {
  background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="17 11 21 7 17 3"></polyline><line x1="21" y1="7" x2="9" y2="7"></line><polyline points="7 21 3 17 7 13"></polyline><line x1="3" y1="17" x2="15" y2="17"></line></svg>');
}

.tb-icon-delete {
  background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 6h18"></path><path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"></path><path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"></path><line x1="10" y1="11" x2="10" y2="17"></line><line x1="14" y1="11" x2="14" y2="17"></line></svg>');
}

.tb-icon-relation {
  background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"></path><polyline points="15 3 21 3 21 9"></polyline><line x1="10" y1="14" x2="21" y2="3"></line></svg>');
}

.tb-icon-style {
  background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"></circle><path d="M8 14s1.5 2 4 2 4-2 4-2"></path><line x1="9" y1="9" x2="9.01" y2="9"></line><line x1="15" y1="9" x2="15.01" y2="9"></line></svg>');
}

.tb-icon-structure {
  background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="7" height="7"></rect><rect x="14" y="3" width="7" height="7"></rect><rect x="14" y="14" width="7" height="7"></rect><rect x="3" y="14" width="7" height="7"></rect></svg>');
}

.tb-icon-undo {
  background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 10h10a8 8 0 1 1 0 16H3"></path><polyline points="3 6 7 2 3 10 7 6"></polyline></svg>');
}

.tb-icon-redo {
  background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 10H11a8 8 0 1 0 0 16h10"></path><polyline points="21 6 17 2 21 10 17 6"></polyline></svg>');
}

.tb-icon-save {
  background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"></path><polyline points="17 21 17 13 7 13 7 21"></polyline><polyline points="7 3 7 8 15 8"></polyline></svg>');
}

.tb-icon-fullscreen {
  background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M8 3H5a2 2 0 0 0-2 2v3m18 0V5a2 2 0 0 0-2-2h-3m0 18h3a2 2 0 0 0 2-2v-3M3 16v3a2 2 0 0 0 2 2h3"></path></svg>');
}

.tb-icon-exit-fullscreen {
  background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M8 3v3a2 2 0 0 1-2 2H3m18 0h-3a2 2 0 0 1-2-2V3m0 18v-3a2 2 0 0 1 2-2h3M3 16h3a2 2 0 0 1 2 2v3"></path></svg>');
}

.toolbar-desc {
  display: none;
}

.style-li{
  position: relative;
}

:deep(.custom-select-options li) {
padding: 0 10px !important;
}

.node-s {
  animation: nodeShow 0.3s;
  display: block;
}

.node-h {
  animation: nodeHide 0.3s;
}

@keyframes nodeHide {
  0% {
      opacity: 1;
      transform: translateX(0);
  }
  100% {
      opacity: 0;
      transform: translateX(110%);
  }
}

@keyframes nodeShow {
  0% {
      opacity: 0;
      transform: translateX(110%);
  }
  10% {
      opacity: 1;
      transform: translateX(100%);
  }
  100% {
      opacity: 1;
      transform: translateX(0);
  }
}

.zIndex {
  position: relative;
  z-index: 30;
}

.zIndex2 {
  position: relative;
  z-index: 33;
}

.zIndex3 {
  position: relative;
  z-index: 32;
}

.zIndex4 {
  position: relative;
  z-index: 31;
}

.backColor {
  width: 93px;
  height: 30px;
  border: 1px solid #ccc;
  border-radius: 3px;
  margin-left: -40px;
  box-shadow: 0 1px 0 1px rgb(0 0 0 / 4%);
  cursor: pointer;
  background-color: #549688;
}

.back-col {
  position: absolute;
  top: 0;
  left: 60px;
  z-index: 40;
}

.node-but {
  display: flex;
  padding: 5px 0;
}

.node-but button {
  flex: 1;
  margin-right: 5px;
  background-color: #fff;
  border: 1px solid #ccc;
  border-radius: 3px;
  padding: 5px 10px;
  cursor: pointer;
  font-size: 12px;
}

.node-but button:last-child {
  margin: 0;
}

.style-title {
  font-size: 16px;
  font-weight: bold;
  padding: 5px 0 10px 0;
}

.style-li img{
  position: absolute;
  top: 0;
  right: 0;
  z-index: 1;
  width: 15px;
  height: 15px;
  cursor: pointer;
}
.style-list {
  display: flex;
  padding: 5px 0;
}

.node-left {
  display: flex;
  padding-right: 10px;
}

.node-left > span {
  display: inline-block;
  width: 80px;
  line-height: 32px;
  padding-right: 10px;
  box-sizing: border-box;
}

.padd {
  padding-right: 0;
}

.node-style {
  position: absolute;
  right: 0;
  top: 50%;
  background-color: #fff;
  border-bottom-left-radius: 5px;
  border-top-left-radius: 5px;
  padding: 20px;
  box-shadow: rgba(0, 0, 0, 0.06) 0 2px 16px 0;
  z-index: 11;
  width: 320px;
  height: 550px;
  margin-top: -270px;
  display: none;
}

.mindMapContainer {
  width: 100%;
  height: calc(100% - 60px);
  border: 1px solid #e8e8e8;
  border-radius: 4px;
}

:deep(.custom-select){
width: 94px;
margin-left: -40px;
}

.full-screen{
background: #fff;
width: 100vw;
height: 100vh;
position: fixed;
top: 0;
left: 0;
z-index: 100;
}

/* 在已有的图标样式下面添加新的图标样式 */

.tb-icon-format {
  background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 3v4a1 1 0 0 0 1 1h4"></path><path d="M17 21h-10a2 2 0 0 1 -2 -2v-14a2 2 0 0 1 2 -2h7l5 5v11a2 2 0 0 1 -2 2z"></path><line x1="9" y1="9" x2="10" y2="9"></line><line x1="9" y1="13" x2="15" y2="13"></line><line x1="9" y1="17" x2="15" y2="17"></line></svg>');
}

.tb-icon-formula {
  background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="4" y1="9" x2="20" y2="9"></line><line x1="4" y1="15" x2="20" y2="15"></line><line x1="10" y1="3" x2="8" y2="21"></line><line x1="16" y1="3" x2="14" y2="21"></line></svg>');
}

.tb-icon-frame {
  background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect><line x1="3" y1="9" x2="21" y2="9"></line><line x1="9" y1="21" x2="9" y2="9"></line></svg>');
}

.tb-icon-note {
  background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path><polyline points="14 2 14 8 20 8"></polyline><line x1="16" y1="13" x2="8" y2="13"></line><line x1="16" y1="17" x2="8" y2="17"></line><polyline points="10 9 9 9 8 9"></polyline></svg>');
}

.tb-icon-ai {
  background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 2c5.523 0 10 4.477 10 10s-4.477 10-10 10S2 17.523 2 12 6.477 2 12 2zm0 4a2 2 0 1 0 0 4 2 2 0 1 0 0-4zM6.5 9.75A1.75 1.75 0 1 0 6.5 13.25 1.75 1.75 0 1 0 6.5 9.75zm11 0a1.75 1.75 0 1 0 0 3.5 1.75 1.75 0 1 0 0-3.5zM8 16a4 4 0 0 0 8 0"></path></svg>');
}

.toolbar-tooltip {
  position: relative;
  background-color: #333;
  color: #fff;
  padding: 6px 12px;
  border-radius: 4px;
  font-size: 12px;
  text-align: center;
  margin-top: 8px;
  opacity: 1;
  width: 100%;
  box-sizing: border-box;
  transition: all 0.3s ease;
  z-index: 100;
  display: none; /* 隐藏工具提示 */
}

.toolbar-tooltip.show {
  opacity: 1;
}

/* 添加响应式设计 */
@media screen and (max-width: 768px) {
  .tb-btn {
    width: 40px;
    height: 40px;
    padding: 3px 0;
  }
  
  .tb-icon {
    width: 18px;
    height: 18px;
  }
  
  .tb-label {
    font-size: 10px;
    margin-top: 3px;
  }
  
  .toolbar-group {
    padding: 0 3px;
    margin-right: 3px;
  }
}

@media screen and (max-width: 480px) {
  .toolbar-inner {
    flex-wrap: nowrap;
    overflow-x: auto;
    padding-bottom: 5px;
  }
  
  .tb-btn {
    width: 36px;
    height: 36px;
  }
  
  .tb-label {
    font-size: 9px;
    margin-top: 2px;
  }
}

/* 修改全屏模式下的样式 */
.full-screen {
  position: fixed !important;
  top: 0 !important;
  left: 0 !important;
  width: 100vw !important;
  height: 100vh !important;
  z-index: 9999 !important;
  background-color: white !important;
  margin: 0 !important;
  padding: 10px !important;
  overflow: hidden !important;
  display: flex !important;
  flex-direction: column !important;
  box-sizing: border-box !important;
}

.full-screen .toolbar {
  position: relative !important;
  width: 100% !important;
  z-index: 10000 !important;
  flex-shrink: 0 !important;
  margin-bottom: 10px !important;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1) !important;
}

.full-screen .mindMapContainer {
  flex: 1 !important;
  width: 100% !important;
  height: calc(100vh - 80px) !important; /* 考虑 padding 和工具栏高度 */
  margin: 0 !important;
  border: none !important;
}

/* 确保非全屏内容在全屏模式下隐藏 */
.full-screen ~ .mindMapContainer {
  display: none !important;
}

.full-screen .mind-map {
  width: 100% !important;
  height: 100% !important;
}

/* 确保非全屏模式下的正常显示 */
.mindMapContainer:not(.full-screen) {
  width: 100%;
  height: 100%;
  min-height: 500px;
  position: relative;
}
</style>
